package org.zebra.tenant.mybatis;

import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.NullValue;
import net.sf.jsqlparser.schema.Table;

/**
 * 增强多租户拦截器，可以根据配置 where 条件是否带租户id
 *
 * @author zhanghongbin
 */
public final class TenantLineInnerPlusInterceptor extends TenantLineInnerInterceptor {

    private boolean whereHasTenantId;

    public TenantLineInnerPlusInterceptor(final TenantLineHandler tenantLineHandler, boolean whereHasTenantId) {
        super(tenantLineHandler);
        this.whereHasTenantId = whereHasTenantId;
    }

    public Expression buildTableExpression(final Table table, final Expression where, final String whereSegment) {
        if (this.whereHasTenantId) {
            return super.buildTableExpression(table, where, whereSegment);
        } else {
            if (super.getTenantLineHandler().getTenantId() instanceof NullValue) {
                return null;
            } else {
                return super.buildTableExpression(table, where, whereSegment);
            }
        }
    }
}
